/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.workflow.service.usertask.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.bpm.engine.impl.identity.Authentication;
import com.je.common.base.DynaBean;
import com.je.common.base.mapper.query.Condition;
import com.je.common.base.spring.SpringContextHolder;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.workflow.service.user.WorkFlowUserService;
import com.je.workflow.service.usertask.CurrentUserParam;
import com.je.workflow.service.usertask.vo.UserTaskVo;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.util.*;
import java.util.function.Consumer;
import static com.je.workflow.service.usertask.vo.UserTaskVo.JudgmentDay;

/**
 * 审批告知
 */
@Service(value = "approvalNoticeService")
public class CurrentUserApprovalNotice extends AbstractCurrentUserService{

    @Override
    public Map<String, Object> getTask(CurrentUserParam upcomingParam) {
        ConditionsWrapper conditionsWrapper = buildWrapper(upcomingParam, false);
        return getRunTask(conditionsWrapper, upcomingParam);
    }

    @Override
    public Long getBadge(CurrentUserParam upcomingParam) {
        ConditionsWrapper conditionsWrapper = buildWrapper(upcomingParam , true);
        buildPreApproveWrapper(conditionsWrapper);
        return abstractGetRunTaskBadge("JE_WORKFLOW_APPROVALNOTICE", conditionsWrapper);
    }

    private Map<String, Object> getRunTask(ConditionsWrapper conditionsWrapper, CurrentUserParam upcomingParam) {
        buildPreApproveWrapper(conditionsWrapper);
        return abstractGetRunTask("JE_WORKFLOW_APPROVALNOTICE", conditionsWrapper, upcomingParam.getPage());
    }

    private void buildPreApproveWrapper(ConditionsWrapper conditionsWrapper) {
        conditionsWrapper.eq("APPROVALNOTICE_TOUSER_ID", Authentication.getAuthenticatedUser().getDeptId());
    }

    public ConditionsWrapper buildWrapper(CurrentUserParam upcomingParam,Boolean isBadge) {
        ConditionsWrapper conditionsWrapper = ConditionsWrapper.builder();
        //如果是审批告知 显示的是未读数
        if (isBadge) {
            conditionsWrapper.eq("APPROVALNOTICE_XXZT_CODE", "0");
        }
        if (!Strings.isNullOrEmpty(upcomingParam.getStartTime()) && !Strings.isNullOrEmpty(upcomingParam.getEndTime())) {
            conditionsWrapper.ge("SY_CREATETIME", upcomingParam.getStartTime() + " 00:00:00");
            conditionsWrapper.le("SY_CREATETIME", upcomingParam.getEndTime() + " 59:59:59");
        }

        if (!Strings.isNullOrEmpty(upcomingParam.getUserName())) {
            List<Condition> conditions = new ArrayList<>();
            conditions.add(buildCondition("APPROVALNOTICE_TITLE", upcomingParam.getUserName()));
            conditions.add(buildCondition("APPROVALNOTICE_CONTENT", upcomingParam.getUserName()));
            conditions.add(buildCondition("APPROVALNOTICE_FROMUSER", upcomingParam.getUserName()));
            conditions.add(buildCondition("APPROVALNOTICE_TOUSER", upcomingParam.getUserName()));
            Consumer<ConditionsWrapper> tConsumer = i -> {
                for (Condition c : conditions) {
                    queryBuilderService.condition(i, c, null);
                }
            };
            conditionsWrapper.and(tConsumer);
        }

//        if (!Strings.isNullOrEmpty(upcomingParam.getSort())) {
//            String[] sortArray = upcomingParam.getSort().split(",");
//            List<String> sortIds = Arrays.asList(sortArray);
//            conditionsWrapper.in("EXECUTION_PROCESS_KEY", sortIds);
//        }
        return conditionsWrapper;
    }
    @Override
    public Map<String, Object> abstractGetRunTask(String tableCode, ConditionsWrapper conditionsWrapper, Page page) {
        conditionsWrapper.orderByDesc( "SY_CREATETIME");
        List<UserTaskVo> result = new ArrayList<>();
        List<DynaBean> list = metaservice.select(tableCode, page, conditionsWrapper);
        for (DynaBean dynaBean : list) {
            result.add(buildRunTask(dynaBean));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("rows", result);
        map.put("totalCount", page.getTotal());
        return map;
    }

    public  UserTaskVo buildRunTask(DynaBean dynaBean) {
        UserTaskVo vo = new UserTaskVo();
        vo.setId(dynaBean.getStr("JE_WORKFLOW_APPROVALNOTICE_ID"));
        vo.setSubmitTime(dynaBean.getStr("SY_CREATETIME"));
        vo.setDelay(dynaBean.getStr(""));
        vo.setTableCode(dynaBean.getStr("APPROVALNOTICE_TABLENAME"));
        vo.setFuncCode(dynaBean.getStr("APPROVALNOTICE_FUNCCODE"));
        vo.setPkValue(dynaBean.getStr("APPROVALNOTICE_PKID"));
        String collectTime = dynaBean.getStr("");
        vo.setPiid(dynaBean.getStr("APPROVALNOTICE_PIID"));
        vo.setContext(dynaBean.getStr("APPROVALNOTICE_CONTENT"));
        vo.setSubmitUserId(dynaBean.getStr("APPROVALNOTICE_FROMUSER_ID"));
        vo.setSubmitUserName(dynaBean.getStr("APPROVALNOTICE_FROMUSER"));
        vo.setIsReadCode(dynaBean.getStr("APPROVALNOTICE_XXZT_CODE"));
        vo.setIsReadName(dynaBean.getStr("APPROVALNOTICE_XXZT_NAME"));
        WorkFlowUserService workFlowUserService = SpringContextHolder.getBean(WorkFlowUserService.class);
        if (!Strings.isNullOrEmpty(workFlowUserService.getUserPhotoById(dynaBean.getStr("APPROVALNOTICE_FROMUSER_ID")))) {
            String photoJson = workFlowUserService.getUserPhotoById(dynaBean.getStr("APPROVALNOTICE_FROMUSER_ID"));
            if (!Strings.isNullOrEmpty(photoJson)) {
                try {
                    JSONObject jsonObject = JSONArray.parseArray(photoJson).getJSONObject(0);
                    vo.setSubmitUserPhoto(jsonObject.getString("fileKey"));
                } catch (Exception e) {
                    e.printStackTrace();
                    vo.setSubmitUserPhoto("");
                }
            }
        } else {
            vo.setSubmitUserPhoto("");
        }

        if (Strings.isNullOrEmpty(collectTime)) {
            vo.setCollect("0");
        } else {
            vo.setCollect("1");
        }
        buildTitle(dynaBean, vo);
        return vo;
    }
    private static void buildTitle(DynaBean dynaBean, UserTaskVo vo) {
        String title = dynaBean.getStr("APPROVALNOTICE_TITLE");
        try {
            String day = JudgmentDay(dynaBean.getStr("SY_CREATETIME"));
            if (day == null) {
                day = dynaBean.getStr("SY_CREATETIME").substring(0, 10);
            }

            try{
                title = String.format(title, "（" + day + "）");
            }catch (Exception e){
                e.printStackTrace();
            }
            vo.setTitle(title);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
